import React, { useState, useEffect } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Chip,
  Typography,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Button,
  Pagination,
  Alert,
  CircularProgress,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Switch,
  FormControlLabel,
  Tooltip,
} from '@mui/material';
import { Refresh, Visibility, Code, Error, Lock } from '@mui/icons-material';
import { useLog } from '../../../hooks';
import { SysLog, RequestMethod, UserRole } from '../../../types';
import {
  formatDateTime,
  formatCostTime,
  getResponseCodeColor,
  formatRequestMethod,
  isErrorRequest,
  formatJsonString,
  truncateText,
  extractFileInfo,
} from '../../../utils';
import { userStorage } from '../../../utils/api';

const SystemLogs: React.FC = () => {
  const { fetchSysLogs, fetchSysLogDetail, loading, error } = useLog();
  const [logs, setLogs] = useState<SysLog[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(20);
  
  // 筛选条件
  const [userId, setUserId] = useState<string>('');
  const [requestMethod, setRequestMethod] = useState<string>('all');
  const [operation, setOperation] = useState<string>('');
  const [errorOnly, setErrorOnly] = useState(false);
  
  // 详情对话框
  const [selectedLog, setSelectedLog] = useState<SysLog | null>(null);
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [detailLoading, setDetailLoading] = useState(false);
  
  // 获取当前用户信息
  const currentUser = userStorage.get();
  const isAdmin = currentUser?.role === UserRole.ADMIN || currentUser?.role === UserRole.SUPERADMIN;

  // 加载日志数据
  const loadLogs = async (page = currentPage) => {
    try {
      const params = {
        page,
        size: pageSize,
        userId: userId ? parseInt(userId) : undefined,
        requestMethod: requestMethod !== 'all' ? requestMethod : undefined,
        operation: operation || undefined,
        errorOnly,
      };
      
      const response = await fetchSysLogs(params);
      setLogs(response.logs);
      setTotal(response.total);
      setTotalPages(response.totalPages);
      setCurrentPage(response.pageNum);
    } catch (err) {
      console.error('加载系统日志失败:', err);
    }
  };

  // 初始加载
  useEffect(() => {
    loadLogs(1);
  }, []);

  // 筛选条件变化时重新加载
  const handleFilter = () => {
    setCurrentPage(1);
    loadLogs(1);
  };

  // 重置筛选条件
  const handleReset = () => {
    setUserId('');
    setRequestMethod('all');
    setOperation('');
    setErrorOnly(false);
    setCurrentPage(1);
    loadLogs(1);
  };

  // 页码变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    setCurrentPage(page);
    loadLogs(page);
  };

  // 查看详情
  const handleViewDetail = async (log: SysLog) => {
    if (!isAdmin) {
      // 非管理员用户显示基本信息，不发送请求
      setSelectedLog(log);
      setDetailDialogOpen(true);
      return;
    }

    // 管理员用户获取详细信息
    setDetailLoading(true);
    try {
      const detailLog = await fetchSysLogDetail(log.id);
      setSelectedLog(detailLog);
      setDetailDialogOpen(true);
    } catch (err) {
      console.error('获取日志详情失败:', err);
    } finally {
      setDetailLoading(false);
    }
  };

  // 获取请求方法颜色
  const getMethodColor = (method: RequestMethod): 'default' | 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' => {
    switch (method) {
      case RequestMethod.GET:
        return 'info';
      case RequestMethod.POST:
        return 'success';
      case RequestMethod.PUT:
        return 'warning';
      case RequestMethod.DELETE:
        return 'error';
      default:
        return 'default';
    }
  };

  if (loading && logs.length === 0) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box>
      {!isAdmin && (
        <Alert severity="info" sx={{ mb: 3 }}>
          <Typography variant="body2">
            您当前以普通用户身份查看系统日志。您可以查看基本的日志信息，但详细的请求参数、响应数据等敏感信息需要管理员权限才能查看。
          </Typography>
        </Alert>
      )}

      {/* 筛选条件 */}
      <Box sx={{ mb: 3, display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
        <TextField
          size="small"
          label="用户ID"
          value={userId}
          onChange={(e) => setUserId(e.target.value)}
          type="number"
          sx={{ width: 120 }}
        />

        <FormControl size="small" sx={{ minWidth: 120 }}>
          <InputLabel>请求方法</InputLabel>
          <Select
            value={requestMethod}
            label="请求方法"
            onChange={(e) => setRequestMethod(e.target.value)}
          >
            <MenuItem value="all">全部</MenuItem>
            <MenuItem value={RequestMethod.GET}>GET</MenuItem>
            <MenuItem value={RequestMethod.POST}>POST</MenuItem>
            <MenuItem value={RequestMethod.PUT}>PUT</MenuItem>
            <MenuItem value={RequestMethod.DELETE}>DELETE</MenuItem>
            <MenuItem value={RequestMethod.PATCH}>PATCH</MenuItem>
          </Select>
        </FormControl>

        <TextField
          size="small"
          label="操作描述"
          value={operation}
          onChange={(e) => setOperation(e.target.value)}
          sx={{ width: 150 }}
        />

        <FormControlLabel
          control={
            <Switch
              checked={errorOnly}
              onChange={(e) => setErrorOnly(e.target.checked)}
              size="small"
            />
          }
          label="仅显示错误"
        />

        <Button variant="contained" onClick={handleFilter} disabled={loading}>
          筛选
        </Button>
        <Button variant="outlined" onClick={handleReset} disabled={loading}>
          重置
        </Button>
        <IconButton onClick={() => loadLogs(currentPage)} disabled={loading}>
          <Refresh />
        </IconButton>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {/* 统计信息 */}
      <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
        共 {total} 条记录，第 {currentPage} / {totalPages} 页
      </Typography>

      {/* 日志表格 */}
      <TableContainer component={Paper}>
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>ID</TableCell>
              <TableCell>用户</TableCell>
              <TableCell>操作</TableCell>
              <TableCell>方法</TableCell>
              <TableCell>URL</TableCell>
              <TableCell>状态码</TableCell>
              <TableCell>耗时</TableCell>
              <TableCell>时间</TableCell>
              <TableCell>操作</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {logs.map((log) => (
              <TableRow key={log.id} hover sx={{ backgroundColor: isErrorRequest(log) ? 'error.light' : 'inherit' }}>
                <TableCell>{log.id}</TableCell>
                <TableCell>
                  <Box>
                    <Typography variant="body2">
                      {log.username || '未知用户'}
                    </Typography>
                    {log.userId && (
                      <Typography variant="caption" color="text.secondary">
                        ID: {log.userId}
                      </Typography>
                    )}
                  </Box>
                </TableCell>
                <TableCell>
                  <Tooltip title={log.operation}>
                    <Typography variant="body2" noWrap sx={{ maxWidth: 150 }}>
                      {log.operation}
                    </Typography>
                  </Tooltip>
                </TableCell>
                <TableCell>
                  <Chip
                    label={formatRequestMethod(log.requestMethod)}
                    color={getMethodColor(log.requestMethod)}
                    size="small"
                  />
                </TableCell>
                <TableCell>
                  <Tooltip title={log.requestUrl}>
                    <Typography variant="body2" noWrap sx={{ maxWidth: 200 }}>
                      {log.requestUrl}
                    </Typography>
                  </Tooltip>
                </TableCell>
                <TableCell>
                  <Chip
                    label={log.responseCode || 'NULL'}
                    color={getResponseCodeColor(log.responseCode) as any}
                    size="small"
                  />
                </TableCell>
                <TableCell>
                  <Typography variant="body2" color={log.costTime > 5000 ? 'error.main' : 'text.primary'}>
                    {formatCostTime(log.costTime)}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography variant="body2">
                    {formatDateTime(log.createdAt)}
                  </Typography>
                </TableCell>
                <TableCell>
                  <Tooltip title={isAdmin ? "查看详情" : "查看基本信息（详细信息需要管理员权限）"}>
                    <IconButton 
                      size="small" 
                      onClick={() => handleViewDetail(log)}
                      disabled={detailLoading}
                    >
                      {!isAdmin ? <Lock /> : <Visibility />}
                    </IconButton>

                  </Tooltip>
                  {isErrorRequest(log) && (
                    <Tooltip title="错误请求">
                      <IconButton size="small" color="error">
                        <Error />
                      </IconButton>
                    </Tooltip>
                  )}
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* 分页 */}
      {totalPages > 1 && (
        <Box sx={{ mt: 3, display: 'flex', justifyContent: 'center' }}>
          <Pagination
            count={totalPages}
            page={currentPage}
            onChange={handlePageChange}
            color="primary"
            disabled={loading}
          />
        </Box>
      )}

      {/* 详情对话框 */}
      <Dialog
        open={detailDialogOpen}
        onClose={() => setDetailDialogOpen(false)}
        maxWidth="lg"
        fullWidth
      >
        <DialogTitle>
          <Box display="flex" alignItems="center" gap={1}>
            系统日志{isAdmin ? '详情' : '基本信息'}
            {selectedLog && isErrorRequest(selectedLog) && (
              <Chip label="错误请求" color="error" size="small" />
            )}
            {!isAdmin && (
              <Chip label="受限访问" color="warning" size="small" icon={<Lock />} />
            )}
          </Box>
        </DialogTitle>
        <DialogContent>
          {selectedLog && (
            <Box sx={{ py: 1 }}>
              {!isAdmin && (
                <Alert severity="warning" sx={{ mb: 3 }}>
                  您当前只能查看基本信息。详细的请求参数、响应数据等敏感信息需要管理员权限才能查看。
                </Alert>
              )}

              {/* 基本信息 */}
              <Typography variant="h6" sx={{ mb: 2 }}>基本信息</Typography>
              <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mb: 3 }}>
                <Typography variant="body2">
                  <strong>日志ID:</strong> {selectedLog.id}
                </Typography>
                <Typography variant="body2">
                  <strong>用户:</strong> {selectedLog.username || '未知用户'} (ID: {selectedLog.userId || 'N/A'})
                </Typography>
                <Typography variant="body2">
                  <strong>操作:</strong> {selectedLog.operation}
                </Typography>
                <Typography variant="body2">
                  <strong>请求方法:</strong> {formatRequestMethod(selectedLog.requestMethod)}
                </Typography>
                <Typography variant="body2">
                  <strong>状态码:</strong> {selectedLog.responseCode || 'NULL'}
                </Typography>
                <Typography variant="body2">
                  <strong>耗时:</strong> {formatCostTime(selectedLog.costTime)}
                </Typography>
                <Typography variant="body2">
                  <strong>IP地址:</strong> {isAdmin ? selectedLog.requestIp : '***敏感信息***'}
                </Typography>
                <Typography variant="body2">
                  <strong>时间:</strong> {formatDateTime(selectedLog.createdAt)}
                </Typography>
              </Box>

              {/* 管理员才能看到的详细信息 */}
              {isAdmin && (
                <>
                  {/* 请求信息 */}
                  <Typography variant="h6" sx={{ mb: 2 }}>请求信息</Typography>
                  <Box sx={{ mb: 3 }}>
                    <Typography variant="body2" sx={{ mb: 1 }}>
                      <strong>URL:</strong>
                    </Typography>
                    <Paper sx={{ p: 2, bgcolor: 'grey.100' }}>
                      <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap' }}>
                        {selectedLog.requestUrl}
                      </Typography>
                    </Paper>
                    
                    <Typography variant="body2" sx={{ mb: 1, mt: 2 }}>
                      <strong>调用方法:</strong>
                    </Typography>
                    <Paper sx={{ p: 2, bgcolor: 'grey.100' }}>
                      <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap' }}>
                        {selectedLog.method}
                      </Typography>
                    </Paper>

                    <Typography variant="body2" sx={{ mb: 1, mt: 2 }}>
                      <strong>请求参数:</strong>
                    </Typography>
                    <Paper sx={{ p: 2, bgcolor: 'grey.100', maxHeight: 300, overflow: 'auto' }}>
                      <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap' }}>
                        {formatJsonString(selectedLog.requestParams)}
                      </Typography>
                    </Paper>

                    {/* 文件信息提取 */}
                    {selectedLog.requestParams && extractFileInfo(selectedLog.requestParams).length > 0 && (
                      <Box sx={{ mt: 2 }}>
                        <Typography variant="body2" sx={{ mb: 1 }}>
                          <strong>上传文件:</strong>
                        </Typography>
                        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
                          {extractFileInfo(selectedLog.requestParams).map((file, index) => (
                            <Chip key={index} label={file} size="small" variant="outlined" />
                          ))}
                        </Box>
                      </Box>
                    )}
                  </Box>

                  {/* 响应信息 */}
                  <Typography variant="h6" sx={{ mb: 2 }}>响应信息</Typography>
                  <Paper sx={{ p: 2, bgcolor: 'grey.100', maxHeight: 400, overflow: 'auto' }}>
                    <Typography variant="body2" component="pre" sx={{ whiteSpace: 'pre-wrap' }}>
                      {formatJsonString(selectedLog.responseData)}
                    </Typography>
                  </Paper>
                </>
              )}

              {/* 非管理员的受限提示 */}
              {!isAdmin && (
                <Box sx={{ mt: 3 }}>
                  <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Lock color="warning" />
                    受限信息
                  </Typography>
                  <Alert severity="info">
                    以下信息需要管理员权限才能查看：
                    <ul style={{ margin: '8px 0', paddingLeft: '20px' }}>
                      <li>详细的请求URL和调用方法</li>
                      <li>请求参数和响应数据</li>
                      <li>上传文件信息</li>
                      <li>完整的IP地址</li>
                    </ul>
                    如需查看完整信息，请联系系统管理员。
                  </Alert>
                </Box>
              )}
            </Box>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDetailDialogOpen(false)}>关闭</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default SystemLogs; 